package pkg

import (
	"crypto/hmac"
	"crypto/sha1"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"github.com/hashicorp/go-uuid"
	"io"
	"io/ioutil"
	"net/http"
	gourl "net/url"
	"strconv"
	"strings"
	"time"
)

func calcAuthorization(secretId string, secretKey string) (auth string, datetime string, err error) {
	timeLocation, _ := time.LoadLocation("Etc/GMT")
	datetime = time.Now().In(timeLocation).Format("Mon, 02 Jan 2006 15:04:05 GMT")
	signStr := fmt.Sprintf("x-date: %s", datetime)

	// hmac-sha1
	mac := hmac.New(sha1.New, []byte(secretKey))
	mac.Write([]byte(signStr))
	sign := base64.StdEncoding.EncodeToString(mac.Sum(nil))

	auth = fmt.Sprintf("{\"id\":\"%s\", \"x-date\":\"%s\", \"signature\":\"%s\"}",
		secretId, datetime, sign)

	return auth, datetime, nil
}

func urlencode(params map[string]string) string {
	var p = gourl.Values{}
	for k, v := range params {
		p.Add(k, v)
	}
	return p.Encode()
}

func UserAuth(idcard string, name string) error {
	// 云市场分配的密钥Id
	secretId := "fqrZR6anV2HcOT7T"
	// 云市场分配的密钥Key
	secretKey := "71DY0bmuTmAFw23pkd9nVTElHZKWzTrG"
	// 签名
	auth, _, _ := calcAuthorization(secretId, secretKey)

	// 请求方法
	method := "GET"
	reqID, err := uuid.GenerateUUID()
	if err != nil {
		panic(err)
	}
	// 请求头
	headers := map[string]string{"Authorization": auth, "request-id": reqID}

	// 查询参数
	queryParams := make(map[string]string)
	queryParams["idcard"] = idcard
	queryParams["name"] = name
	// body参数
	bodyParams := make(map[string]string)

	bodyParamStr := urlencode(bodyParams)
	// url参数拼接
	url := "https://ap-shanghai.cloudmarket-apigw.com/service-3n5dlvot/get/idcard/inclusive"

	if len(queryParams) > 0 {
		url = fmt.Sprintf("%s?%s", url, urlencode(queryParams))
	}

	bodyMethods := map[string]bool{"POST": true, "PUT": true, "PATCH": true}
	var body io.Reader = nil
	if bodyMethods[method] {
		body = strings.NewReader(bodyParamStr)
		headers["Content-Type"] = "application/x-www-form-urlencoded"
	}

	client := &http.Client{
		Timeout: 5 * time.Second,
	}
	request, err := http.NewRequest(method, url, body)
	if err != nil {
		panic(err)
	}
	for k, v := range headers {
		request.Header.Set(k, v)
	}
	response, err := client.Do(request)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()

	bodyBytes, err := ioutil.ReadAll(response.Body)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(bodyBytes))
	var t T
	json.Unmarshal(bodyBytes, &t)
	if t.Success == false {
		return fmt.Errorf(t.Msg)
	}
	if t.Code == 400 {
		return fmt.Errorf(t.Msg)
	}
	if t.Data.Desc == "不一致" && t.Code == 200 {
		return fmt.Errorf("用户姓名和身份证号不匹配")
	}
	birthday := t.Data.Birthday
	format := time.Now().Format("20060102")
	birthdays, _ := strconv.Atoi(birthday)
	formats, _ := strconv.Atoi(format)
	if formats-birthdays < 18000000 {
		return fmt.Errorf("用户是否成年")
	}
	return nil
}

type T struct {
	Msg     string `json:"msg"`
	Success bool   `json:"success"`
	Code    int    `json:"code"`
	Data    struct {
		Result   int    `json:"result"`
		OrderNo  string `json:"order_no"`
		Desc     string `json:"desc"`
		Sex      string `json:"sex"`
		Birthday string `json:"birthday"`
		Address  string `json:"address"`
	} `json:"data"`
}
